package com.example.todolist.receiver

import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.example.todolist.util.LoggerTag.Companion.MAIN_NOTI
import com.example.todolist.util.NotificationUtil
import com.example.todolist.viewmodel.TodoListViewModel

class NotificationReceiver : BroadcastReceiver() {
    private val NOTI_TITLE = "待办事件过期提醒"
    private val NOTI_CONTENT = "默认通知内容"
    private val TODO_NOTI_ID = 1
    override fun onReceive(context: Context, intent: Intent) {

        val notiTitle = intent.getStringExtra("title") ?: NOTI_TITLE
        val notiContent = intent.getStringExtra("content") ?: NOTI_CONTENT
        val todoId = intent.getIntExtra("todoId", -1)
        // 发送通知
        val notification = NotificationUtil.createNotification(
            context, notiTitle, notiContent, "todoId", NOTI_TITLE
        )
        Log.d(MAIN_NOTI, "onReceive:---->触发了 ")

        val manager = context.getSystemService(NotificationManager::class.java)
        manager.notify(TODO_NOTI_ID, notification)

        // 修改过期状态
//        val viewModel =
//            ViewModelProvider(context as ViewModelStoreOwner)[TodoListViewModel::class.java]
//        viewModel.updateIsExpired(todoId, true)
        // 2. 发送本地广播通知应用内更新状态
        if (todoId != -1) {
            val localIntent = Intent(ACTION_TODO_EXPIRED).apply {
                putExtra("todoId", todoId)
            }
            LocalBroadcastManager.getInstance(context).sendBroadcast(localIntent)
            Log.d(MAIN_NOTI, "本地广播发送:---->---->todoid:$todoId")
        }
    }

    companion object {
        const val ACTION_TODO_EXPIRED = "com.example.todolist.ACTION_TODO_EXPIRED"
    }
}